/* Copyright (c) 2009, Enric Rodriguez (enrodri86@gmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 	- Redistributions of source code must retain the above copyright
 * 	notice,	this list of conditions and the following disclaimer.
 * 	- Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * 	- Neither the name of the <ORGANIZATION> nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package es.enrodri86.mmo.auth.sgs;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Hashtable;
import java.util.Map;

import es.enrodri86.mmo.auth.server.BasicHTTPAuthServer;
import es.enrodri86.mmo.auth.shared.AuthException;
import es.enrodri86.mmo.auth.shared.Captcha;
import es.enrodri86.mmo.auth.shared.Game;
import es.enrodri86.mmo.auth.shared.GameServer;
import es.enrodri86.mmo.auth.shared.LoginException;

public abstract class BasicSGSAuthServer extends BasicHTTPAuthServer {

	private Map<String, Game> gameList;
	private Map<String, GameServer> serverList;
	private Map<String, SGSService> connList;

	public BasicSGSAuthServer(){
		gameList = new Hashtable<String, Game>();
		serverList = new Hashtable<String, GameServer>();
		connList = new Hashtable<String, SGSService>();
	}

	public void chooseGame(String sessionKey, String g) throws IOException,
	AuthException {

		//TODO nothing :P
		//it does not matter which game did the user select, what matters is
		// the game server.
	}

	public void chooseGameServer(String sessionKey, String gsid) throws IOException, AuthException {
		SGSService service = connList.get(gsid);
		if(service != null){
			service.send(sessionKey,getUserBinding(sessionKey));
		}else{
			AuthException ae = new AuthException();
			ae.setDescription("Internal server error, please try again later.");
			//TODO send a message to the system manager
			throw ae;
		}

	}

	public Map<String, Game> getGameList(String sessionKey) {
		return gameList;
	}

	public Map<String, GameServer> getGameServerList() {
		return serverList;
	}


	public void run() {
		while(true){
			try {
				ServerSocket ss = new ServerSocket(4392);
				while(true){
					Socket s = ss.accept();
					InetSocketAddress sa = (InetSocketAddress) s.getRemoteSocketAddress();
					//We only trust connections from the LAN environment.
					if(sa.getAddress().isSiteLocalAddress() || sa.getAddress().isLoopbackAddress()){
						new SGSService(s).start();
					}else{
						s.close();
					}
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}

	private class SGSService extends Thread{

		private Socket s;
		private Game g;
		private ObjectOutputStream oos;
		private GameServer gs;

		private boolean ooslock;

		public SGSService(Socket s){
			this.s = s;
			try {
				oos = new ObjectOutputStream(s.getOutputStream());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public synchronized void send(String sessionKey, Object userBinding) {
			if(sessionKey == null || userBinding == null){
				//TODO send a message to the manager
				return;
			}
			while(ooslock){
				try {
					wait();
				} catch (InterruptedException e) {}
			}
			ooslock = true;
			try {
				oos.writeObject(sessionKey);
				oos.writeObject(userBinding);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ooslock = false;
			notifyAll();
		}


		public void run() {
			if(oos == null){
				end();
				return;
			}
			try {
				ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
				while(true){
					try {
						Object r = ois.readObject();
						if(r.getClass().equals(String.class)){
							//This is a session key of a user who has logged off.
							releaseKey((String)r);
						}else if(r.getClass().equals(GameServer.class)){
							gs = (GameServer) r;

							serverList.put(gs.getId(), gs);
							gameList.get(g.getId()).addServerID(gs.getId());

						}else if(r.getClass().equals(Game.class)){
							g = (Game) r;
							if(!gameList.containsKey(g.getId())){
								gameList.put(g.getId(), g);
							}
						}

					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			end();
		}


		private void end() {
			try {
				s.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			serverList.get(gs.getId()).setStatus(GameServer.STATUS_DOWN);
		}
	}

}
